module RealTime
  class << self
    # 上证指数: sh000001 深证成指: sz399001 沪深300: sh000300 北证50: bj899050 创业板指: sz399006
    # RealTime.index "sh000001"
    # https://vip.stock.finance.sina.com.cn/mkt/
    def index(code)
      conn = Faraday.new(
        url: "https://hq.sinajs.cn/",
        headers: {
          "Referer" => "https://vip.stock.finance.sina.com.cn/",
          "Sec-Fetch-Mode" => "no-cors",
          "Sec-Fetch-Site" => "cross-site",
          "User-Agent" => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
        }
      ) do |f|
        f.response :raise_error
        f.adapter Faraday.default_adapter
      end
      response = conn.get do |req|
        req.params = { _: "0.6105760628325401", list: "#{code}" }
      end
      response_body = response.body.force_encoding('GBK').encode('UTF-8')
      "TODO 补齐所有数据，可查大盘和个股，实时数据，包含分笔数据"
      data = response_body.match(/="(.*?)";/)[1].split(',')
      keys = ["name", "open", "yes_close", "close", "low"]
      Hash[keys.zip(data.first(5))]
    end

    # https://finance.sina.com.cn/realstock/company/sh600673/nc.shtml  B/S点
    # https://finance.sina.com.cn/finance/hq/upbs/sh601899.js
    # RealTime.buy_sell_point "sh601899"
    def buy_sell_point(code)
      response = Faraday.new(url: "https://finance.sina.com.cn/finance/hq/upbs/#{code}.js").get
      response_body = response.body.force_encoding('GBK').encode('UTF-8')
      json_str = response_body[/var\s+\w+\s*=\s*({.*?})\s*(?:\/\/|\/\*)/m, 1]
      json_str.gsub!(/\\(.)/) { $1 == '\\' ? '\\' : $1 } if json_str
      JSON.parse(json_str)
    end

    # RealTime.sina_today_all
    # http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?page=1&num=100&sort=symbol&asc=1&node=hs_a&symbol=&_s_r_a=init
    def sina_today_all
      if Time.now - Time.strptime(JSON.parse($Redis.get("600011"))["ticktime"], "%H:%M:%S") > 120
        Robot.send_alert "心跳超时"
      end
      conn = Faraday.new(url: "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?")
      arr = Parallel.map((9..55).to_a, in_processes: 1, progress: false) do |time|
        # delay_millisecond(1, rand(450..600)) {}
        puts time; delay_millisecond(1, rand(450..600)) {}
        response = conn.get do |req|
          req.params = { num: "100", sort: "code", asc: "0", node: "hs_a", page: "#{time}", symbol: "", _s_r_a: "" }
        end
        unless response.status == 200
          Robot.send_alert "RealTime.sina_today_all 接口封禁"; break
        end
        JSON.parse(response.body)
      end
      arr.flatten
    end

    # http://market.finance.sina.com.cn/pricehis.php?symbol=sh600900&startdate=2025-03-21&enddate=2025-04-21
    # RealTime.per_price('sh600900', '2025-03-21', '2025-04-21')
    def per_price(symbol, startdate, enddate)
      doc = Nokogiri::HTML(URI.open("http://market.finance.sina.com.cn/pricehis.php?symbol=sh600900&startdate=2025-03-21&enddate=2025-04-21"))
      arr = []
      doc.css('tbody').css('tr').each do |board|
        ob = {}
        ob["price"] = board.css('td')[0].text
        ob["volume"] = board.css('td')[1].text
        ob["percentage"] = board.css('td')[2].text
        arr << ob
      end
      arr
    end

    # http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh600011&scale=5&ma=3&datalen=10
    # RealTime.kline "sz399001", 5, 3, 10
    def kline(code, scale, ma, len)
      delay_millisecond(1, 288){}
      conn = Faraday.new(url: "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData",)
      response = conn.get do |req|
        req.params = { symbol: "#{code}", scale: "#{scale}", ma: "#{ma}", datalen: "#{len}", }
      end
      JSON.parse(response.body)
    end

    # RealTime.hs_kline "sz399001"
    # http://115.190.26.14/api/data?symbol=sh600011
    def hs_kline(code)
      conn = Faraday.new(url: "http://115.190.26.14/api/data",)
      response = conn.get do |req|
        req.params = { symbol: "#{code}" }
      end
      JSON.parse(response.body)
    end

    # 获取个股实时资金流向
    # https://stockpage.10jqka.com.cn/600011/
    # RealTime.ths_flow 600011
    def ths_flow(code)
      delay_millisecond(1, 188){}
      score = Nokogiri::HTML(URI.open("https://stockpage.10jqka.com.cn/#{code}/")).css('.analyze-num').text
      res = Faraday.get("https://stockpage.10jqka.com.cn/spService/#{code}/Funds/realFunds/free/1/")
      unless res.status == 200
        Robot.send_alert "RealTime.ths_flow 接口封禁"
        raise "RealTime.ths_flow RealTime.ths_flow 接口封禁"
      end
      json = JSON.parse(res.body)
      json.store("score", score)
      json.delete("field")
      json
    end

    # RealTime.hs_ths_flow 600011
    # http://115.190.26.14/api/ths_flow?symbol=600011
    def hs_ths_flow(code)
      conn = Faraday.new(url: "http://115.190.26.14/api/ths_flow",)
      response = conn.get do |req|
        req.params = { symbol: "#{code}" }
      end
      JSON.parse(response.body)
    end

    # RealTime.ali_ths_flow 600011
    # http://39.101.143.157:6060/api/ths_flow?symbol=600011
    def ali_ths_flow(code)
      conn = Faraday.new(url: "http://39.101.143.157:6060/api/ths_flow",)
      response = conn.get do |req|
        req.params = { symbol: "#{code}" }
      end
      JSON.parse(response.body)
    end


    # http://wyyz-test1203.fcv3.1725649566763474.cn-hangzhou.fc.devsapp.net/flow/600103-600011-600022
    def fc_ths_flow(code)
      res = Faraday.get("http://wyyz-test1203.fcv3.1725649566763474.cn-hangzhou.fc.devsapp.net/flow/#{code}")
      json = JSON.parse(res.body)
      json.delete("field")
      json
    end

    # https://stockpage.10jqka.com.cn/000001/funds/#funds_sszjlx
    # RealTime.funds_sszjlx 600011
    def funds_sszjlx(code)
      funds_sszjlx = Nokogiri::HTML(URI.open("https://stockpage.10jqka.com.cn/#{code}/funds/#funds_sszjlx"))
      funds_sszjlx.css('#history_table_free')

    end
  end
end
